package com.example.thread;

import java.util.ArrayList;
import java.util.List;

public class NotifyFreeLock {

    //添加volatile，使t2能够得到通知
    volatile List lists = new ArrayList();

    volatile Boolean lock=true;

    public  void add(Object o) {
        lists.add(o);
    }

    public static void main(String[] args) throws Exception{
        NotifyFreeLock notifyFreeLock = new NotifyFreeLock();
        Thread t2 =  new Thread(()->{
            synchronized (notifyFreeLock.lock){
                System.out.println("线程2=="+notifyFreeLock.lists.size());
                try {
                    notifyFreeLock.lock.notify();
                    notifyFreeLock.lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t1 =  new Thread(()->{
            synchronized (notifyFreeLock.lock){
                for(int i=0;i<10;i++){
                    notifyFreeLock.add(new Object());
                    System.out.println("添加对象 size="+notifyFreeLock.lists.size());
                    if (notifyFreeLock.lists.size()==5){
                        try {
                          //  t2.join();
                            notifyFreeLock.lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });

        t1.start();
        t2.start();
    }

}
